<template>
  <s-layout :tabbarshow="false" id="layout" navbar="normal" :title="`借支申请`" :autoBack="true" leftIconColor="$uni-text-color"
    :bgColor="'rgba(0,0,0,0)'" :titleStyle="{ color: '#fff', fontSize: '32rpx' }">

    <view class="container"
      :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`, paddingTop: (safeAreaInsets?.top + 44) + 'px' }">

      <!-- 表单盒子 -->
      <view class="form_box area">
        <scroll-view scroll-y :enable-back-to-top="true" class="comprehensive">
          <!-- 表单结构 -->
          <uni-forms ref="relRef" v-model="state.formData" :rules="state.rules" validateTrigger="bind" labelWidth="120">

            <uni-forms-item name="department_id" label="部门：" required>
              <uni-easyinput @tap="projectSwitch" :disabled="true" placeholder="请选择部门"
                v-model="project_title" :inputBorder="false">
              </uni-easyinput>
              <!-- v-if="FormData.type == 2 || FormData.type == 3" -->
              <!-- <u-form-item @tap="projectSwitch" required="true" :borderBottom="false" :labelWidth="100" label="部门：" prop="department_id" ref="department_id">
                <u--input clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请选择部门" v-model="project_title" border="none"></u--input>
            </u-form-item> -->
            </uni-forms-item>

            <uni-forms-item name="information" label="账户信息：" required>
              <uni-easyinput @tap="returnedSwitch" :disabled="true" placeholder="请选择账户信息"
                v-model="state.formData.information" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="quantity" label="借款金额：" required>
              <uni-easyinput placeholder="请输入借款金额" v-model="state.formData.quantity" type="number" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="content" label="借款理由" required class="flex">
              <view class="flex-vertical">
                <uni-easyinput type="textarea" v-model="state.formData.content" placeholder="请输入借款理由"></uni-easyinput>
              </view>
            </uni-forms-item>
            <view class="cards">
              <view class="title">
                <view class="red">*</view>图片:
              </view>
              <view class="img">
                <view class="imgexample">
                  <image class="images" :src="`${baseUrl}/uploads/uniapp_image/staff/jietiao.png`" mode="scaleToFill" />
                  <view class="imgexample_name" @click="preview">
                    <image class="eximages" :src="`${baseUrl}/uploads/uniapp_image/staff/yanjing.png`"
                      mode="scaleToFill" />
                    <text>示例图片</text>
                  </view>
                </view>
                <u-upload :fileList="state.fileList1" @afterRead="imageUpload" @delete="deletePic" name="4" multiple
                  :maxCount="1">
                </u-upload>
              </view>

            </view>
          </uni-forms>

        </scroll-view>
      </view>

    </view>

  </s-layout>
  <!-- 账户 -->
  <!-- 底部弹出组件 && 回款账户弹出 -->
  <s-popup-list :skipPage="'/subpackage/staff/workbench/returned_info/returned_info_add'" :placeholder="'搜索回款账户'" @selectedData="returned_switchTitle" :current_page="returned_current_page"
    :last_page="returned_last_page" @pageEvent="returned_pageEvent" :searchBoxIsShow="false" :arrayList="returnedDataList"
    ref="returned_popupListRef" :popupTitle="'选择回款账户'" :listingName="'回款账户列表(仅支持银行卡)'" :showGoLink="'#'"
    :isBank="true"></s-popup-list>

  <!-- 底部弹出组件 && 部门弹出 -->
  <s-project-class @selectedData="project_switchTitle" 
  :arrayList="projectDataList" ref="project_popupListRef"
  :searchBoxIsShow="false"   :showGoLink="false"></s-project-class>

  <!-- 底部提交按钮 -->
  <view >
    <s-button @netWork="submitForm" :text="text"></s-button>
  </view>

 

</template>

<script setup>
import sheep from '@/sheep';
import { ref, reactive, unref } from 'vue';
import { onShow,onLoad } from '@dcloudio/uni-app';
import { baseUrl } from "@/sheep/config";
import { information, quantity, content,department_id } from '@/sheep/validate/form';
const { safeAreaInsets } = uni.getSystemInfoSync();
const urls1 = ref([{  
    src2: 'https://pic.616pic.com/bg_w1180/00/05/27/BRWwlrYqg3.jpg',  
}]);
const text = ref("提交");
const state = reactive({
  fileList1: [],
  formData: {
    information: '',
    quantity: '',
    content: '',
    uploadimg:'',
    returned_id:'',     // 回款信息 ID
    department_id:''    // 部门 ID
  },
  rules: {
    information,
    quantity,
    content,
    department_id
  }
})
onShow((options)=>{
  returnedDataList.value =[]
  returned_page.value = 1
  getReturnedInfoData()   // 获取回款账户列表
})

onLoad(() => {
  let params={
          is_all:'1',
          is_include_main:'1'
      }
  projectList(params)           // 获取部门列表
})

//图片预览
const preview =()=>{
  uni.previewImage({
        urls: [`${baseUrl}`+`/uploads/uniapp_image/staff/jietiao.png`], // 需要预览的图片链接列表
      });

}
// 获取回款信息
const returnedDataList = ref([])
    const returned_current_page = ref()
    const returned_last_page =  ref()
    const returned_page = ref(1)
    const returned_id = ref('')
    const returned_popupListRef = ref(null)
    const returned_keywords = ref()
    // 点击弹出
    const returnedSwitch = () => {
        returned_popupListRef.value.open()
    }
    // 封装回款账户接口
    const getReturnedInfoData = async () => {
        let params = {
            filter: JSON.stringify({
                bank_name: returned_keywords.value,
                type: 'bank',
            }),
            op: JSON.stringify({
                bank_name: 'LIKE',
                type: '=',
            }),
            page: returned_page.value,
        };
        const res = await sheep.$api.returned_info.getReturnedInfo(params);
      returnedDataList.value = [...returnedDataList.value, ...res?.data.rows];
    
        // 改写数组
        returnedDataList.value.forEach(item => {
            let bank_number = item.bank_number.substr(0, 4) + '****' + item.bank_number.substr(-4)
            item.title = item.bank.name + '（' + bank_number + '）'
            item.logo = item.bank.logo
        });
        returned_current_page.value = res.data.current_page;
        returned_last_page.value = res.data.last_page;
    }
    // 回款账户列表分页
    const returned_pageEvent = () => {
        if (returned_current_page.value < returned_last_page.value) {
            returned_page.value += 1;
        } else {
            return;
        }
        getReturnedInfoData();
    }

    // 拿过来的项目数据
    const returned_switchTitle = (item) => {
      state.formData.information = item.title
        returned_id.value = item.id
    }
//提交
const relRef = ref();
const submitForm = async () => {

  console.log(state.formData,'数据');

  // #ifdef MP
  sheep.$platform.useProvider('wechat').subscribeMessage(['apply_notice','apply_result_notice']);
    // #endif
  const validate = await unref(relRef)
    .validate()
    .catch((error) => {
    });
  if (!validate) return;
  if (state.fileList1 == '') {
    sheep.$helper.toast('请上传图片');
		return false
	}
  uni.$u.throttle(() => {
    state.formData.uploadimg = postData.value.join(',')
    let parpam={
      return_id: returned_id.value,
      title: state.formData.content,
      price: state.formData.quantity,
      images: state.formData.uploadimg,
      department_id:state.formData.department_id,
    }
    sheep.$api.borrowing.getBorrowingAdd(parpam).then((res) => {
      if (res.code == 1) {
        sheep.$helper.toast(res.msg);
        setTimeout(() => {
          sheep.$router.back(true)
        }, 500)
      } else {
        sheep.$helper.toast(res.msg);
      }
    })
  },1000)
};
// 删除图片
const deletePic = (event) => {
  state.fileList1.splice(event.index, 1);
  postData.value.splice(event.index, 1);
};

// 新增图片
const imageUpload = async (event) => {
  let lists = [].concat(event.file);
  let fileListLen = state.fileList1.length;
  lists.map((item) => {
    state.fileList1.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const url = await uploadFilePromise(lists[i].url);
    let item = state.fileList1[fileListLen];
    state.fileList1.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: sheep.$url.cdn(url),
    });
    fileListLen++;
  }
};
const postData = ref([])
async function uploadFilePromise(tempUrl) {
  let { url } = await sheep.$api.app.upload(tempUrl, 'ugc');
  postData.value.push(url)
  return url;


};


//获取部门列表
const projectDataList = ref([])
const project_title = ref('')
const project_popupListRef = ref(null)
// 点击弹出
const projectSwitch = () => {
    project_popupListRef.value.open()
}
// 封装部门列表接口
const projectList = async (params = null) => {
    const res = await sheep.$api.app.getDepartment(params);
    projectDataList.value = res.data;
};
// 拿过来的部门数据
const project_switchTitle = (item) => {
    project_title.value = item.jointTitles
    state.formData.department_id = item.id
}




</script>

<style scoped lang="scss">
 @import '../compentns/public.scss';
//  修改内容
.edit_button{
    height: 144rpx;
    width: 90%;
    padding: 0 5%;
    background-color: #ffffff;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 98;
    display: flex;
    .del{width: 276rpx;
      height: 90rpx;
border-radius: 50rpx;
border: 2rpx solid $uni-color-primary;
color: $uni-color-primary;
 font-family: PingFangSC;
color: $uni-color-primary;
font-weight: $uni-font-weight;
font-size: 34rpx;}
.edit{
  margin-left: 20rpx;
  width: 454px;
height: 90rpx;
border-radius: 50rpx;
font-family: PingFangSC;
color: #FFFFFF;
font-weight: $uni-font-weight;
font-size: 34rpx;
background: linear-gradient(90deg, rgba(0, 56, 247, 1) 0%, rgba(77, 139, 255, 1) 100%);
}
}

:deep(.uni-forms) {
  .uni-forms-item.is-direction-left {
    &:nth-last-child(2) {
      .uni-forms-item__label {
        background: $uni-bg-color;
        margin-top: -10rpx;
      }
      flex-direction: column !important;
      height: auto;
    }

  }
}
// 滚动
.comprehensive{
        width: calc(100% - 40rpx);
        background-color: rgba(0, 0, 0, 0);
        margin: 0 20rpx;
        height: 73vh;
}
//图片
.cards {
  width: 100%;
  border-radius: 16rpx;
  background-color: #FFFFFF;
  margin-bottom: 120rpx;
  padding-bottom: 20rpx;
  .img{
    display: flex;
    margin-right: 10rpx;
    .imgexample{
      margin: 30rpx 20rpx 30rpx 0;
      width: 140rpx;
    height: 139rpx;
      border-radius: 16rpx;
      position: relative;
      .images{
        width: 140rpx;
        height: 139rpx;
      }
      .imgexample_name{
        position: absolute;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        border-radius: 16rpx;
        background-color: rgba(0, 0, 0, 0.4);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .eximages{
          width: 36rpx;
          height: 26rpx;
        }
        text{
          font-size: 22rpx;
          color:$uni-bg-color;
          margin-top: 10rpx;
        }
      }
    }
  }
    :deep(.u-upload) {
      margin: 30rpx 0;
      width: 100% !important;
      background: #fff !important;
      .u-upload__wrap{
        flex-direction: row !important;
        flex-wrap: wrap !important;
        justify-content: flex-start !important;
      }
}
.title{
      display: flex;
      .red{color: #FF0000; padding-top: 12rpx;}
    }
.uploadimg {
  width: 60rpx;
  height: 48rpx;
}
}
:deep(.is-disabled){
  .uni-easyinput__placeholder-class{
    color: $uni-color-primary !important;
  }   

}
</style>